import { Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'el-pagination',
  templateUrl: './pagination.component.html'
})
export class PaginationComponent implements OnInit, OnChanges {
  @Input() small: boolean = false;
  @Input() total: number = 0;
  @Input() layout: Array<string> = ['prev', 'pager', 'next', 'total'];;
  @Input('page-size') pageSize: number = 10;
  @Input('page-sizes') pageSizes: Array<number> = [10, 20, 30, 40, 50, 100];
  @Input('page-count') pageCount: number = 0;
  @Input() model: number = 1;
  @Output() modelChange: EventEmitter<number> = new EventEmitter();
  @Input() showPager: boolean = true;
  @Input() showPrev: boolean = true;
  @Input() showNext: boolean = true;
  @Input() showTotal: boolean = true;
  @Input() showSize: boolean = true;
  @Input() showJumper: boolean = true;
  constructor() { }

  ngOnChanges(changes: SimpleChanges): void {
    if (!changes)
      return;
    if (changes.total && changes.total.isFirstChange())
      return;
    this.updateLayout();
  }

  ngOnInit(): void {
    if (!this.pageCount && this.total === undefined) {
      return console.warn('el-pagination required [total]');
    }
    this.updateLayout();
  }

  showLayout(ElName: string, layout: any) {
    var /** @type {?} */ member = layout.find(function (name: any) { return name === ElName; });
    return !!member;
  }

  nextHandle(step: number) {
    var /** @type {?} */ nextPage = this.model + step;
    this.model = nextPage < 1 ? 1 : nextPage > this.total ? this.total : nextPage;
    this.modelChange.emit(this.model);
  }

  updatePageSize(nextPageSize: any) {
    this.pageCount = Math.ceil(this.total / Number(nextPageSize));
    this.model = 1;
  }

  updateLayout() {
    if (this.total === undefined || this.total === null) {
      this.total = Math.round(this.pageCount * this.pageSize);
    }
    this.pageCount = Math.ceil(this.total / this.pageSize) || 1;
    this.showPager = this.showLayout('pager', this.layout);
    this.showPrev = this.showLayout('prev', this.layout);
    this.showNext = this.showLayout('next', this.layout);
    this.showTotal = this.showLayout('total', this.layout);
    this.showSize = this.showLayout('size', this.layout);
    this.showJumper = this.showLayout('jumper', this.layout);
  }

}
